//
//  PersonDetailViewController.m
//  TestProject6
//
//  Created by JasonLee on 14/12/11.
//  Copyright (c) 2014年 JasonLee. All rights reserved.
//

#import "PersonDetailViewController.h"
#import "ZHPickView.h"
#import "ProtocolManager.h"
#import "Common.h"
#import "PersonViewController.h"
#import "TransforController.h"

#define LOGINSTATUS @"loginStatus.plst"

@interface PersonDetailViewController ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate,ZHPickViewDelegate>
@property(nonatomic,strong)ZHPickView *pickview;
@property(nonatomic,strong)NSIndexPath *indexPath;
@property (strong, nonatomic) UILabel *lbGender;
@property (strong, nonatomic) UILabel *lbBirthday;
@property (strong, nonatomic) UILabel *lbPublic;
@property (strong, nonatomic) UITextField *txt_username;
@property (strong, nonatomic) NSMutableArray *array_textField;
@property (strong, nonatomic) UITapGestureRecognizer *lbGenderTapGestureRecognizer;
@property (strong, nonatomic) UITapGestureRecognizer *lbBirthdayTapGestureRecognizer;
@property (strong, nonatomic) NSMutableArray *viewList;
@property (strong, nonatomic) UITextField *txt_actived;
@property (strong, nonatomic) UIScrollView *view_scroll_temp;
@end

@implementation PersonDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    NSLog(@"childViewControllers:%@", self.navigationController.childViewControllers);
    NSLog(@"Loading PersonDetailViewController;");
    
    [self initData];
    [self setGesture];
    self.navigationItem.title = @"我的资料";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(onCancelBarButtonPressed)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(onDoneBarButtonPressed)];
    _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];

    UIView *view_navagationBar = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 65)];
    view_navagationBar.backgroundColor = [Common colorWithRGB:0x18aaf6];
    [self.view addSubview:view_navagationBar];
    
//    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
//    //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
//    tapGestureRecognizer.cancelsTouchesInView = NO;
//    //将触摸事件添加到当前view
//    [_tableView addGestureRecognizer:tapGestureRecognizer];
    
    self.array_textField = [[NSMutableArray alloc]init];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_lbPublic resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initData{
    //NSLog(@"%@", [_person getModel]);
    _viewList = [[NSMutableArray alloc]init];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0:
            return 3;
            break;
        case 1:
            return 2;
        default:
            return 0;
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = nil;
    NSArray *array = nil;
    UITextField *txtDetail = nil;
    //CGRect rect = [UIScreen mainScreen].bounds;
    CGRect cellRect;
    //CGSize screenSize = rect.size;
    CGSize cellSize;
    //NSLog(@"%li",indexPath.row);
    switch (indexPath.section) {
        case 0:{
            cell = [tableView dequeueReusableCellWithIdentifier:@"topGroup"];
            if(cell == nil){
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"topGroup"];
                cellRect = cell.bounds;
                cellSize = cellRect.size;
                array = [self getDetail:indexPath];
                //NSLog(@"%@", array);
                cell.textLabel.text = array.firstObject;
                [cell setAccessoryType:UITableViewCellAccessoryNone];
                if(indexPath.row == 0){
                        txtDetail = [[UITextField alloc]initWithFrame:CGRectMake(80, 2, cellSize.width - 80, cellSize.height)];
                        txtDetail.text = [array objectAtIndex:1];
                        txtDetail.clearButtonMode = UITextFieldViewModeWhileEditing;
                    self.txt_username = txtDetail;
                    self.txt_username.delegate =self;
                    [_viewList addObject:txtDetail];
                        [cell addSubview:txtDetail];
                }else if(indexPath.row == 1){
                        _lbGender = [[UILabel alloc]initWithFrame:CGRectMake(80, 2, cellSize.width - 80, cellSize.height)];
                        _lbGender.text = [array objectAtIndex:1];
                    _lbGender.tag = 9001;
                    _lbGender.userInteractionEnabled = YES;
                    [_lbGender addGestureRecognizer:_lbGenderTapGestureRecognizer];
                    [_viewList addObject:_lbGender];
                        [cell addSubview:_lbGender];
                }else if(indexPath.row == 2){
                        _lbBirthday = [[UILabel alloc]initWithFrame:CGRectMake(80, 2, cellSize.width - 80, cellSize.height)];
                        _lbBirthday.text = [array objectAtIndex:1];
                    _lbBirthday.tag = 9002;
                    _lbBirthday.userInteractionEnabled = YES;
                    [_lbBirthday addGestureRecognizer:_lbBirthdayTapGestureRecognizer];
                    [_viewList addObject:_lbBirthday];
                        [cell addSubview:_lbBirthday];
                }
            }
            break;
        }
        case 1:{
            cell = [tableView dequeueReusableCellWithIdentifier:@"bottomGroup"];
            if(cell == nil){
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"bottomGroup"];
                cellRect = cell.bounds;
                cellSize = cellRect.size;
                array = [self getDetail:indexPath];
                cell.textLabel.text = array.firstObject;
                [cell setAccessoryType:UITableViewCellAccessoryNone];
                txtDetail = [[UITextField alloc]initWithFrame:CGRectMake(80, 2, cellSize.width - 80, cellSize.height)];
                txtDetail.text = [array objectAtIndex:1];
                txtDetail.clearButtonMode = UITextFieldViewModeWhileEditing;
                [self.array_textField addObject:txtDetail];
                txtDetail.delegate = self;
                //CGSize titleSize = [detailLabel.text sizeWithFont:detailLabel.font constrainedToSize:CGSizeMake(MAXFLOAT, 30)];
                //detailLabel.frame = CGRectMake(screenSize.width - titleSize.width - 10, cellSize.height / 2 - titleSize.height + 10, titleSize.width, titleSize.height);
                [_viewList addObject:txtDetail];
                [cell addSubview:txtDetail];
            }
            break;
        }
        default:
            break;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark 添加手势
-(void)setGesture{
    /*添加点按手势*/
    //创建手势对象
    //UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singleTapAction:)];
    _lbGenderTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(lbGenderSingleTapAction:)];
    _lbBirthdayTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(lbBirthdaySingleTapAction:)];
    UITapGestureRecognizer *defaultTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(defaultSingleTapAction:)];
    //设置手势属性
    _lbGenderTapGestureRecognizer.numberOfTapsRequired=1;
    _lbBirthdayTapGestureRecognizer.numberOfTapsRequired = 1;
    defaultTapGestureRecognizer.numberOfTapsRequired = 1;//设置点按次数，默认为1，注意在iOS中很少用双击操作
    _lbGenderTapGestureRecognizer.numberOfTouchesRequired=1;
    _lbBirthdayTapGestureRecognizer.numberOfTouchesRequired = 1;
    defaultTapGestureRecognizer.numberOfTouchesRequired = 1;//点按的手指数
    //添加手势到对象(注意，这里添加到了控制器视图中，而不是图片上，否则点击空白无法隐藏导航栏)
    //lbGenderTapGestureRecognizer.delegate = self;
    [self.view addGestureRecognizer:defaultTapGestureRecognizer];

}

#pragma mark - 手势操作
- (void)lbGenderSingleTapAction:(UITapGestureRecognizer *)gesture{
    if(_pickview != nil){
        [_pickview remove];
    }
//    NSLog(@"==>>PersonDetailViewController-->>lbGenderSingleTapAction||action's been actived.");
    [self.txt_username resignFirstResponder];
    for(UITextField *field in self.array_textField){
        [field resignFirstResponder];
    }
    NSArray *array=@[@"男",@"女"];
    _pickview=[[ZHPickView alloc] initPickviewWithArray:array isHaveNavControler:NO];
    _pickview.delegate=self;
    _lbPublic = _lbGender;
    [_pickview show];
}
- (void)lbBirthdaySingleTapAction:(UITapGestureRecognizer *)gesture{
    if(_pickview != nil){
        [_pickview remove];
    }
//    NSLog(@"==>>PersonDetailViewController-->>lbBirthdaySingleTapAction||action's been actived.");
    [self.txt_username resignFirstResponder];
    for(UITextField *field in self.array_textField){
        [field resignFirstResponder];
    }
    NSDate *date=[NSDate dateWithTimeIntervalSinceNow:0];
    _pickview=[[ZHPickView alloc] initDatePickWithDate:date datePickerMode:UIDatePickerModeDate isHaveNavControler:NO];
    _pickview.delegate=self;
    _lbPublic = _lbBirthday;
    [_pickview show];
}
- (void)defaultSingleTapAction:(UITapGestureRecognizer *)gesture{
    if(_pickview != nil){
        [_pickview remove];
    }
    [self.txt_username resignFirstResponder];
    for(UITextField *field in self.array_textField){
        [field resignFirstResponder];
    }
//    NSLog(@"==>>PersonDetailViewController-->>defaultSingleTapAction||action's been actived.");
}

-(void)toolBarBtnClicked:(ZHPickView *)pickView resultString:(NSString *)resultString{
    
    //NSLog(@"==>>PersonDetailViewController-->>toolBarBtnClicked||(NSString)indexPath.section:%d , (NSString)indexPath.row:%d",_indexPath.section, _indexPath.row);
    //UITableViewCell *cell=[self.tableView cellForRowAtIndexPath:_indexPath];
    //NSLog(@"==>>PersonDetailViewController-->>toolBarBtnClicked||(NSString)_lbPublic.text:%@",_lbPublic.text);
    
    //cell.textLabel.text=resultString;
    _lbPublic.text = resultString;
}

/*
 *  getDetail
 *  NSArray
 *  (NSIndexPath *)indexPath
 *  by Jason
 *  从NSUserDefault中获取数据并填充table view；
 */
- (NSArray *)getDetail:(NSIndexPath *)indexPath{
    //NSLog(@"%@", [_person getModel]);
    NSArray *array = nil;
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:{
                array = [[NSArray alloc]initWithObjects:@"昵称", [[NSUserDefaults standardUserDefaults]objectForKey:@"Username"], nil];
                break;
            }
            case 1:{
                array = [[NSArray alloc]initWithObjects:@"性别", [[NSUserDefaults standardUserDefaults]objectForKey:@"Sex"], nil];
                break;
            }case 2:{
                array = [[NSArray alloc]initWithObjects:@"生日", [[NSUserDefaults standardUserDefaults]objectForKey:@"Birthday"], nil];
                break;
            }
            default:
                break;
        }
    }else{
        switch (indexPath.row) {
            case 3:{
                array = [[NSArray alloc]initWithObjects:@"行业", [[NSUserDefaults standardUserDefaults]objectForKey:@"Industry_to"], nil];
                break;
            }
            case 0:{
                array = [[NSArray alloc]initWithObjects:@"邮箱", [[NSUserDefaults standardUserDefaults]objectForKey:@"Email"], nil];
                break;
            }
            case 1:{
                array = [[NSArray alloc]initWithObjects:@"地址", [[NSUserDefaults standardUserDefaults]objectForKey:@"Address"], nil];
                break;
            }
            default:
                break;
        }
    }
    //NSLog(@"==>>PersonDetailController-->>getDetail||array:%@", array);
    return array;
}

- (void)onCancelBarButtonPressed{
    if(_pickview != nil){
        [_pickview remove];
    }
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"是否放弃对资料的修改" message:@"" delegate:self cancelButtonTitle:@"放弃" otherButtonTitles:@"继续编辑", nil];
    alertView.alertViewStyle=UIAlertViewStyleDefault;
    alertView.tag = 10086;
    [alertView show];
    //[self.navigationController popViewControllerAnimated:YES];
}

- (void)onDoneBarButtonPressed{
    if(_pickview != nil){
        [_pickview remove];
    }
    NSString *username = [self getTextFromList:0];
    NSString *gender = [self getTextFromList:1];
    NSString *birthday = [self getTextFromList:2];
    NSString *industry = [self getTextFromList:3];
    NSString *email = [self getTextFromList:3];
    NSString *address = [self getTextFromList:4];
    if([username isEqualToString:@""]){
        [[Common shareInstance]showAlertViewWithTitle:nil text:@"请填写昵称" dismissTime:0.8];
        return;
    }
    if ([TransforController getNSStringLength:username] < 4 || [TransforController getNSStringLength:username] > 20) {
        [[Common shareInstance]showAlertViewWithTitle:nil text:@"昵称长度应小于20位大于4位" dismissTime:0.8];
        return;
    }
    if(![email isEqualToString:@""]){
        if (![TransforController validateEmail:email]){
            [[Common shareInstance]showAlertViewWithTitle:nil text:@"邮箱格式不正确！" dismissTime:0.8];
            return;
        }
    }
//    [TransforController statusLoadingBar];
    [[ProtocolManager shareInstance] update:username gender:gender birthday:birthday industry:industry email:email address:address target:self selector:@selector(getUpdateCallBack:)];
    //[self.navigationController popViewControllerAnimated:YES];
}

- (void)getUpdateCallBack:(NSDictionary *)dic{
    if(dic == nil){
        return;
    }
    NSLog(@"==>>PersonDetailViewController-->>getUpdateCallBack||dic | %@",dic);
    NSUserDefaults *accountInfo = [NSUserDefaults standardUserDefaults];
    
    [accountInfo setObject: [self getTextFromList:0] forKey:@"Username"];
    [accountInfo setObject:[self getTextFromList:1] forKey:@"Sex"];
    [accountInfo setObject:[self getTextFromList:2] forKey:@"Birthday"];
//    [accountInfo setObject:[self getTextFromList:3] forKey:@"Industry_to"];
    [accountInfo setObject:[self getTextFromList:3] forKey:@"Email"];
    [accountInfo setObject:[self getTextFromList:4] forKey:@"Address"];
    [accountInfo synchronize];
    
//    NSMutableDictionary *savingDic = [NSMutableDictionary dictionary];
//    [savingDic setValue:[dic objectForKey:@"Username"] forKey:@"Username"];
//    [savingDic setValue:[dic objectForKey:@"Sex"] forKey:@"Sex"];
//    [savingDic setValue:[dic objectForKey:@"Birthday"] forKey:@"Birthday"];
//    [savingDic setValue:[dic objectForKey:@"Email"] forKey:@"Email"];
//    [savingDic setValue:[dic objectForKey:@"Address"] forKey:@"Address"];
//    [savingDic setValue:[dic objectForKey:@"Industry_to"] forKey:@"Industry_to"];
//    [savingDic writeToFile:[FileManager getFullDocumentPath:LOGINSTATUS]atomically:YES];
//    NSString *filePath = [FileManager getFullDocumentPath:LOGINSTATUS];
//    NSDictionary *tempDic = [NSDictionary dictionaryWithContentsOfFile:filePath];
    [[Common shareInstance] showAlertViewWithTitle:nil text:@"修改成功" dismissTime:0.8];
    [self.UpdateSuccessDelegate updateUsernameAfterUpdateSuccessed:[self getTextFromList:0]];
//    [TransforController stopStatusAndClear];
    [self.navigationController popViewControllerAnimated:YES];
    
}
- (NSString *)getTextFromList:(int)index{
    NSString *string = ((UILabel *)[_viewList objectAtIndex:index]).text;
//    switch (index) {
//        case 1:
//            string = ((UILabel *)[_viewList objectAtIndex:index]).text;
//            break;
//        case 2:
//            string = ((UILabel *)[_viewList objectAtIndex:index]).text;
//            break;
//        default:
//            string = ((UITextField *)[_viewList objectAtIndex:index]).text;
//            break;
//    }
    NSLog(@"%s || string:%@",__FUNCTION__, string);
    return string;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(alertView.tag == 10086){
        if(buttonIndex == 0){
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.txt_actived = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    self.txt_actived = nil;
}

-(void)viewWillAppear:(BOOL)animated{
    [self registerForKeyboardNotifications];
}

-(void)viewWillDisappear:(BOOL)animated{
    [self removeForKeyboardNotifications];
}

- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    
}

- (void)removeForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
}

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    
//    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
//    self.view_scroll_temp.contentInset = contentInsets;
//    self.view_scroll_temp.scrollIndicatorInsets = contentInsets;
    
    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your application might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= (kbSize.height + 20);
    CGRect rect_txt_actived = self.txt_actived.superview.frame;
    if ((rect_txt_actived.origin.y + rect_txt_actived.size.height) > aRect.size.height) {
        CGPoint scrollPoint = CGPointMake(0.0, self.view.frame.size.height - kbSize.height - self.txt_actived.superview.frame.size.height * 2);
        [self.tableView setContentOffset:scrollPoint animated:YES];
        self.tableView.scrollEnabled = NO;
    }
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
//    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
//    self.view_scroll_temp.contentInset = contentInsets;
//    self.view_scroll_temp.scrollIndicatorInsets = contentInsets;
    
    [self.tableView setContentOffset:CGPointMake(0, -66) animated:YES];
    self.tableView.scrollEnabled = YES;
}


@end
